from django.http import HttpResponse
from django.shortcuts import render
from django.db.models import Avg, Count, Max, Min, Sum, F, Q
from .models import Book,BookOrder,Publisher,Author
# Create your views here.
def avg_view(request):
    result = Book.objects.aggregate(Avg('price'))
    print(result)
    return HttpResponse('查询平均值成功')

def count_view(request):
    result = Book.objects.aggregate(book_count=Count('id'))
    print(result)
    return HttpResponse("查询图书数量成功")

def max_min_view(request):
    result = Author.objects.aggregate(max_age=Max('age'),min_age=Min('age'))
    print(result)
    return HttpResponse("查询最大值和最小值成功")

def sum_view(request):
    result = Book.objects.annotate(total=Sum('bookorder__price')).values('name', 'total')
    print(result)
    return HttpResponse("查询销售总额成功")

def f_view(request):
    Book.objects.update(price=F('price')-10)
    return HttpResponse('图书价格修改成功')

def q_view(request):
    books = Book.objects.filter(Q(price__gte=80) | Q(rating__gte=5)).all()
    for book in books:
        print(book.name, book.price, book.rating)
    return HttpResponse('图书价格大于等于80 或者 评分大于等于5分')
